package cn.tom.controller;

import cn.tom.respjson.RespJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@ControllerAdvice   //统一异常处理
@RestController
public class ErrController {
    /**
     * Logger输出
     */
    private Logger log
            = LoggerFactory.getLogger(cn.tom.tool.Log.class);

    @ResponseBody
    @ExceptionHandler(value = OAuth2Exception.class)
    public Map<String, Object> handleOauth2(OAuth2Exception e) {
        return RespJson.pack(401, "Token 出错", "");
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map<String, Object> errorHandler(Exception ex) {
        log.info(ex.getMessage());
        log.info(String.valueOf(ex.getCause()));
        String msg = getErrInfo(ex.getCause().toString());
        return RespJson.pack(100, msg, "");
    }

    private String getErrInfo(String cause) {
        String msg = "";
        if (cause.indexOf("java.sql") > 0) {
            msg = "SQL出错";
            if (cause.indexOf("1104") >= 0) {
                msg = msg + "-唯一索引出错";
            }
        }
        if (msg.length() < 1) msg = "后端出现异常 [" + cause + "]";
        return msg;
    }
}
